package mr.ali.videoapp.portal.controller;

import mr.ali.videoapp.portal.service.impl.WxaCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wxacode")
public class WxaCodeController {

    @Autowired
    private WxaCodeService wxaCodeService;

    /**
     * 生成无限小程序码（GET 接口，便于前端调用）
     * 示例：/api/wxacode/unlimit?page=pages/index/index&scene=userId_123
     */
    @GetMapping("/unlimit")
    public ResponseEntity<byte[]> getUnlimitedWxaCode(
            @RequestParam String page,
            @RequestParam String scene,
            @RequestParam(required = false) Integer width,
            @RequestParam(required = false) Boolean autoColor,
            @RequestParam(required = false) Integer r,
            @RequestParam(required = false) Integer g,
            @RequestParam(required = false) Integer b,
            @RequestParam(required = false) Boolean isHyaline,
            @RequestParam(required = false) String envVersion) {

        try {
            byte[] imageBytes = wxaCodeService.generateWxaCodeUnlimit(
                    page, scene, width, autoColor, r, g, b, isHyaline, envVersion);

            return ResponseEntity.ok()
                    .header("Content-Type", "image/png")
                    .body(imageBytes);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 可选：返回 base64 图片（用于 JSON 响应）
     */
    @GetMapping("/unlimit/base64")
    public ResponseEntity<Map<String, String>> getUnlimitedWxaCodeBase64(
            @RequestParam String page,
            @RequestParam String scene) {

        try {
            byte[] imageBytes = wxaCodeService.generateWxaCodeUnlimit(page, scene, null, null, null, null, null, null, null);
            String base64Image = "data:image/png;base64," + java.util.Base64.getEncoder().encodeToString(imageBytes);

            Map<String, String> result = new HashMap<>();
            result.put("qrcode", base64Image);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}